<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="../include/laypublic.jsp" %>
<%@ include file="../include/vueComponent.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <title>月度资金计划详情</title>
</head>

<link rel="stylesheet" href="${ctx}/resources/vue-element-lib/detail.css">
<style>
    .unit_img div {
        height: 41px;
    }
</style>
<body>
<div id="app">
    <div class="layui-tab layui-tab-brief" lay-filter="xqxx-tab-all">
        <ul class="layui-tab-title">
            <li id="tbglId" class="layui-this" lay-id="0">月度资金计划详情</li>
<%--            <li id="zgysId" lay-id="1">历史审批信息</li>--%>
        </ul>

        <div class="layui-tab-right">
            <c:if test="${isAuditFlag eq '1'}">
                <template v-if="layId==0">
                    <button type="button" class="layui-btn layui-btn-primary layui-btn-radius" @click="save(0)">保存
                    </button>
                    <button type="button" class="layui-btn layui-btn-radius" @click="save(1)">提交</button>
                </template>
            </c:if>
            <c:if test="${auditTabFlag eq '1'}">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-radius" @click="audit(0)">
                    不同意
                </button>
                <button type="button" class="layui-btn layui-btn-radius" @click="audit(1)">同意</button>
            </c:if>
        </div>
        <div class="layui-tab-content" style="height: 100px;">
            <div class="layui-tab-item layui-show">
                <div class="container">
                    <el-form ref="formRef" label-width="180px" label-suffix="："
                             label-position="left">
                        <div class="title">
                            <h3>项目信息</h3>
                        </div>
                        <el-row>
                            <x-col>
                                <el-form-item label="项目名称">
                                    <el-select v-model="proCode" filterable placeholder="请选择项目名称"
                                               style="width: 100%" @change="queryDetailByWhere" v-if="!id">
                                        <el-option v-for="item in proInfoList" :key="item.proCode" :label="item.proName"
                                                   :value="item.proCode">
                                        </el-option>
                                    </el-select>
                                    <span v-else>{{info.proName}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="归属月份">
                                    <el-date-picker style="width: 100%" type="month"
                                                    v-model="belongDate" @change="queryDetailByWhere"
                                                    placeholder="选择归属月份" value-format="yyyy-MM"></el-date-picker>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="计划编码">
                                    <span>{{info.codes}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="归属公司">
                                    <span>{{info.compName}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <div class="title">
                            <h3>年度预算详情</h3>
                        </div>
                        <div class="unit">
                            <div class="unit_center">
                                <div class="unit_img">
                                    <div class="item" v-for="(item,index) in detailList" :key="index"
                                         v-if="detailList.length>1">
                                        <img src="${ctx}/resources/images/del.png" alt="" v-if="item.isAdd==1"
                                             @click="detailListDel(index)">
                                    </div>
                                </div>
                                <el-table :data="detailList" border>
                                    <el-table-column prop="typeName" label="指标" align="center" width="200">
                                        <template slot-scope="scope">
                                            <%--保证金类支出需要下拉手动--%>
                                            <el-select v-model="scope.row.bondOutType" :placeholder="scope.row.typeName"
                                                       v-if="scope.row.bondOutTypeList&&scope.row.bondOutTypeList.length>0">
                                                <el-option v-for="item in scope.row.bondOutTypeList" :key="item.code"
                                                           :label="item.name" :value="item.code">
                                                </el-option>
                                            </el-select>
                                            <el-popover placement="bottom" width="50" trigger="hover"
                                                        style="opacity: 0" v-else-if="scope.row.types==2">
                                                <div class="el-popover_item">
                                                    <el-button type="button"
                                                               @click="queryTypeByTypeId(scope.row,scope.$index)">
                                                        添加子项
                                                    </el-button>
                                                </div>
                                                <div slot="reference">{{scope.row.typeName}}</div>
                                            </el-popover>
                                            <el-select v-model="scope.row.typeId"
                                                       v-else-if="scope.row.isAdd==1"
                                                       @change="sel($event,scope.$index)">
                                                <el-option v-for="item in scope.row.subAddList" :key="item.typeId"
                                                           :label="item.typeName" :value="item.typeId">
                                                </el-option>
                                            </el-select>
                                            <span v-else>{{scope.row.typeName}}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="currDate" label="日期" align="center" width="200">
                                        <template slot-scope="scope">
                                            <%--政府代付费和项目前期费点击弹出弹窗，编辑信息--%>
                                            <span v-if="scope.row.isList==2" style="cursor: pointer"
                                                  @click="showTips(scope.row)">点击</span>
                                            <el-date-picker style="width: 100%" type="date"
                                                            v-else-if="scope.row.types==3"
                                                            v-model="scope.row.currDate" placeholder="选择日期"
                                                            value-format="yyyy-MM-dd"
                                                            :picker-options="pickerOptions"></el-date-picker>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="金额" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.currAmt" type="number" min="0"
                                                     v-if="scope.row.types==3"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="nextMonth" label="月份" align="center"></el-table-column>
                                    <el-table-column label="金额" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.nextAmt" type="number" min="0"
                                                     v-if="scope.row.types==3&&scope.row.isAdd!=1"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="lowestMonth" label="月份" align="center"></el-table-column>
                                    <el-table-column label="金额" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.lowestAmt" type="number" min="0"
                                                     v-if="scope.row.types==3&&scope.row.isAdd!=1"></x-input>
                                            <el-input disabled v-else></el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <el-dialog title="政府代收费/项目前期费" :visible.sync="tips" width="80%" :before-close="handleClose">
                            <div class="unit">
                                <div class="unit_add">
                                    <button class="layui-btn layuiadmin-btn-admin" type="button" data-type="add"
                                            @click="add">
                                        <i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>添加费用
                                    </button>
                                </div>
                                <div class="unit_center">
                                    <div class="unit_img">
                                        <div class="item" v-for="(item,index) in costList" :key="index"
                                             v-if="costList.length>1">
                                            <img src="${ctx}/resources/images/del.png" alt=""
                                                 @click="del(index)">
                                        </div>
                                    </div>
                                    <el-table :data="costList" border>
                                        <el-table-column label="收款单位" align="center">
                                            <template slot-scope="scope">
                                                <el-select v-model="scope.row.sgOrgId" filterable placeholder="请选择收款单位">
                                                    <el-option v-for="item in orgInfoList" :key="item.id"
                                                               :label="item.compName" :value="item.id">
                                                    </el-option>
                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="费用名称" align="center">
                                            <template slot-scope="scope">
                                                <x-input v-model="scope.row.costName" name="费用名称"></x-input>
                                            </template>
                                        </el-table-column>

                                        <el-table-column label="日期" align="center">
                                            <template slot-scope="scope">
                                                <el-date-picker style="width: 100%" type="date"
                                                                v-model="scope.row.costDate" placeholder="选择日期"
                                                                value-format="yyyy-MM-dd">
                                                </el-date-picker>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="金额" align="center">
                                            <template slot-scope="scope">
                                                <x-input v-model="scope.row.costAmt" type="number" min="0"
                                                         name="金额" @input="sum"></x-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="摘要" align="center">
                                            <template slot-scope="scope">
                                                <x-input v-model="scope.row.memo" name="摘要"></x-input>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <span slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="confirm">确 定</el-button>
                            </span>
                        </el-dialog>
                    </el-form>
                </div>
            </div>

        </div>
    </div>
</div>
<script src="${ctx}/resources/vue-element-lib/jquery.js"></script>
<script>
    let fileArr = [];
    var staticPath = '${fileHttpPre}';
    layui.config({
        base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'set', 'upload', 'table', 'transfer', 'laydate', 'element', 'layer'], function () {
        var $ = layui.$
            , upload = layui.upload
            , table = layui.table
            , element = layui.element
            , layer = layui.layer;

        //选项卡切换监听
        element.on('tab(xqxx-tab-all)', function (data) {
            var layId = $(this).attr('lay-id');
            vm.$data.layId = layId
            if (layId === "0") {
            } else if (layId === "1") {
                loadTable(layId);
            } else if (layId === "2") {

            }
        });

        function loadTable(layId) {
            // 表单
            table.render({
                elem: '#lay-lsspxx-create-manage'
                , url: basePath + '/fiaHistoryProcess/list?proCode=${proCode}'
                , cols: [[
                    {
                        field: 'startTime', title: '发起时间', width: 145, width: 155, templet: function (d) {
                            return layui.util.toDateString(d.startTime, "yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    , {field: 'startRealName', title: '发起人', width: 145}
                    , {field: 'proFlowType', title: '审批阶段', width: 145}
                    , {
                        field: 'dealTime', title: '审批日期', width: 155, templet: function (d) {
                            return layui.util.toDateString(d.dealTime, "yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    , {field: 'dealName', title: '审批人', width: 160}
                    , {
                        field: 'state', title: '审批状态'
                    }
                    , {
                        title: '操作', width: 140, align: 'center', fixed: 'right', templet: function (d) {
                            var optStr = "";
                            optStr += '<a class="layui-btn layui-btn-xs" lay-event="view"><i class="layui-icon layui-icon-form"></i>查看</a>';
                            return optStr;
                        }
                    }
                ]]
                , page: true
                , limit: 10
            });

            // 监听操作列
            table.on('tool(lay-lsspxx-create-manage)', function (obj) {
                var data = obj.data;
                if (obj.event === 'view') {//查看
                    parent.layui.index.openTabsPage(basePath + '/fiaHistoryProcess/toDetail?processId=' + data.processId, '历史流程信息 > 详情');
                }
            });
        }

        ;(function () {
            //定义构造函数
            var Upfile = function (ele, type, opt) {
                this.defaults = {
                    //elem:‘#uploadPic‘	//绑定元素
                    elem: $(ele)	//绑定元素
                    , url: basePath + '/contractInfo/uploadAtt/',
                    data: {
                        types: type
                    },
                    multiple: true,
                    accept: 'file',
                    acceptMime: 'application/zip,application/x-rar-compressed,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf',

                    method: 'post',
                    before: function (obj) { //obj参数包含的信息
                        layer.load(); //上传loading
                    },
                    done: function (res) {
                        //如果上传失败
                        if (res.code > 0) {
                            layer.closeAll('loading'); //关闭loading
                            return layer.msg(res.msg, {icon: 7});
                        }
                        //上传完毕
                        if (res.entity != null && res.entity.length > 0) {
                            fileArr.push(res.entity[0])
                            for (var i in res.entity) {
                                var contractInfo = res.entity[i];
                                var arr = contractInfo.split("|");
                                var imgSrc = "";
                                var suffix = arr[1].substring(arr[1].lastIndexOf(".") + 1, arr[1].length);
                                if (suffix == 'jpg' || suffix == 'png') {
                                    imgSrc = "${fileHttpPre}/" + arr[3];
                                } else {
                                    imgSrc = "${ctx}/resources/images/" + suffix + ".jpg";
                                }
                                $('#' + type + '-upload-more-list')
                                    .append('<div class="layui-upload-img-div" id="upload_img_' + arr[2] + '"><img src="' + imgSrc + '" title="'
                                        + arr[1] + '" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\'' + "${fileHttpPre}"
                                        + arr[3] + '\');">查看</a><a href="javascript:void(0)" onclick="del(\''
                                        + arr[2] + '\')";>删除</a></div><p>' + arr[1] + '</p><input type="hidden" value="'
                                        + contractInfo + '" id="fileAtt_' + arr[2] + '" name="fileAtts" ></input></div> ');
                            }
                        }
                    },
                    allDone: function (obj) { //当文件全部被提交后，才触发
                        layer.closeAll('loading'); //关闭loading
                    },
                    error: function () {
                        layer.closeAll('loading'); //关闭loading
                        //上传失败
                        layer.msg("上传失败，请稍后再试~", {icon: 7});
                    }
                }
                this.options = $.extend({}, this.defaults, opt);
            };

            //定义方法
            Upfile.prototype = {
                init: function () {
                    var _this = this;
                    return layui.use('upload', function () {
                        var upload = layui.upload;

                        //执行实例
                        var uploadInst = upload.render(_this.options);
                    });
                }
            };

            //在插件中使用对象
            $.fn.upfile = function (options) {
                var upfile = new Upfile(this, options);
                return upfile.init();
            }
        })();
        //上传文件
        $('#14-upload-more').upfile(14);
    });

    //删除文件
    function del(index) {
        layui.$("#fileAtt_" + index).remove();
        layui.$("#upload_img_" + index).remove();
    }

    //根据url查看文件
    function showImg(url) {
        var openWin = window.open(url, '', 'left=410,height=768, width=1024, top=200,  toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
    }

    /*核心*/
    var vm = new Vue({
        el: '#app',
        data() {
            return {
                layId: '0',
                id: '',
                proCode: '',//项目名称
                belongDate: '',//归属月份
                info: {},
                procNodeList: [],
                tempNodeList: [],
                detailList: [],
                proInfoList: '',
                pickerOptions: {},
                tips: false,
                costList: [],
                orgInfoList: [],//收款单位
                showTipsObj: {}
            }
        },
        created() {
            let that = this;
            this.id = "${id}";
            this.proCode = "${proCode}";
            this.processId = "${processId}";
            this.queryDetail();
            this.queryProcessList();
        },
        mounted() {

        },
        methods: {
            //展示弹窗
            showTips(e) {
                console.log(e)
                this.costList = [];
                this.showTipsObj = e;
                this.costList = e.costList && e.costList.length > 0 ? e.costList : [];
                this.tips = true;

            },
            confirm() {
                this.detailList.map(el => {
                    if (el.typeId == this.showTipsObj.typeId) {
                        el.costList = this.costList;
                    }
                })
                this.showTipsObj = {};
                this.costList = [];
                this.tips = false;
                this.sum();
            },
            handleClose() {
                this.tips = false;
                this.sum();
            },
            sum() {
                this.detailList.map(el => {
                    if (el.costList && el.costList.length > 0) {
                        let num = 0
                        el.costList.map(el1 => {
                            num += Number(el1.costAmt)
                        })
                        el.currAmt = num;
                    }
                })
                this.$forceUpdate()
            },
            add() {
                let obj = {
                    sgOrgId: '',//合作单位ID或组织架构公司ID
                    costName: '',//费用名称
                    costDate: '',//日期
                    costAmt: '',//费用
                    memo: '',//摘要
                }
                this.costList.push(obj);
                this.sum();
            },
            del(index) {
                this.costList.splice(index, 1);
                this.sum();
            },
            detailListDel(index) {
                this.detailList.splice(index, 1);
            },
            queryDetail() {
                zAjax('/fundsPlan/queryDetail', {id: this.id}).then(res => {
                    if (res.code == 0) {
                        this.info = res.entity.info;
                        if (res.entity.info) this.belongDate = res.entity.info.belongDate;
                        if (res.entity.detailList && res.entity.detailList.length > 0) this.detailList = res.entity.detailList;
                        if (this.belongDate) this.disabledDate();
                        this.orgInfoList = res.entity.orgInfoList;
                        this.proInfoList = res.entity.proInfoList;
                    }

                })
            },
            queryDetailByWhere() {
                if (this.proCode && this.belongDate) {
                    zAjax('/fundsPlan/queryDetailByWhere', {
                        proCode: this.proCode,
                        belongDate: this.belongDate
                    }).then(res => {
                        if (res.code == 0) {
                            this.detailList = res.entity.detailList;
                            this.disabledDate();
                            if (res.entity.info) {
                                this.info.id = res.entity.info.id
                            } else {
                                this.info.id = ''
                            }
                        }
                        console.log(res)
                    })
                }
            },
            queryTypeByTypeId(e, index) {
                console.log(e);
                zAjax('/fundsPlan/queryTypeByTypeId', {
                    typeId: e.typeId,
                    belongDate: this.belongDate
                }).then(res => {
                    console.log(res)
                    let obj = {
                        subAddList: res.entity,
                        isAdd: 1,
                        typeId: '',
                        currDate: '',
                        currAmt: '',
                        types: '3',
                    }
                    this.detailList.splice(index + 1, 0, obj);
                })
            },
            disabledDate() {
                this.pickerOptions = {};
                let now = new Date(this.belongDate) //当前日期
                let days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();//获取当前月多少天
                let monthStartDate = new Date(now.getFullYear(), now.getMonth(), 1)
                let timeStart = Date.parse(monthStartDate);
                let monthEndDate = new Date(now.getFullYear(), now.getMonth(), days)
                let timeEnd = Date.parse(monthEndDate);
                this.pickerOptions.disabledDate = time => (time.getTime() < timeStart) || (time.getTime() > timeEnd)
            },
            sel(e, index) {
                let list = this.detailList[index].subAddList;
                list.map(el => {
                    if (el.typeId == e) {
                        this.detailList[index].bondOutTypeList = el.bondOutTypeList;
                        this.detailList[index].bondOutType = el.bondOutType;
                        this.detailList[index].isList = el.isList;
                    }
                })
                console.log(this.detailList[index])
            },
            error(text) {
                this.$message({
                    message: text,
                    type: 'warning'
                });
            },

            queryProcessList() {
                let that = this;
                zAjax('/fiaHistoryProcess/processList', {processId: that.processId}).then(res => {
                    console.log(res)
                    if (res.success) {
                        that.procNodeList = res.entity.procNodeList;
                        that.tempNodeList = res.entity.tempNodeList;
                    }
                })
            },
            //保存
            save(type) {
                let that = this;
                let obj = {
                    info: that.info,
                    detailList: that.detailList,
                };
                obj.info.proCode = this.proCode;
                obj.info.belongDate = this.belongDate;
                let str = JSON.stringify(obj).replace(/\"/g, '\\"');
                zAjax('/fundsPlan/edit', {bodyStr: str, submitType: type,}).then(res => {
                    if (res.success) {
                        that.$message({message: '保存成功', type: 'success'});
                    } else {
                        that.$message.error(res.msg);
                    }

                })
            },
            audit(status) {
                let that = this;
                $.ajax({
                    type: 'post',
                    url: basePath + '/fundsPlan/auditProcess',  //请求数据接口
                    async: false,
                    data: {
                        id: that.id,
                        processId: that.processId,
                        status: status,
                        auditMsg: that.auditMsg,
                    },
                    success: function (result) {
                        if (result.success) {
                            that.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            setTimeout(function () {
                                // 刷新首页
                                let index = window.parent.layui.admin.tabsPage.index
                                if (index == null) {
                                    window.close();
                                } else {
                                    var iframe = window.parent.layui.admin.tabsBody((index - 1)).find(".layadmin-iframe");
                                    iframe[0].contentWindow.location.reload();
                                    top.layui.admin.closeThisTabs(); // 关闭当前标签页
                                }
                            }, 3000);
                        } else {
                            that.$message.error('保存失败');
                        }
                    }
                });
            }
        }
    })
</script>
</body>
</html>